package com.luych.userModule.service;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.luych.common.page.Page;
import com.luych.userModule.entity.PermissionInfo;
import com.luych.userModule.entity.UserInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final ObjectMapper objectMapper;
    private final RestTemplate restTemplate;

    @Autowired
    public UserService(ObjectMapper objectMapper, RestTemplate restTemplate) {
        this.objectMapper = objectMapper;
        this.restTemplate = restTemplate;
    }

    public Page page(Page page, String keywords) throws InvocationTargetException, IllegalAccessException {
        page = restTemplate.getForObject(
                "http://USERCENTER/user?pageNumber={1}&pageSize={2}&sortName={3}&sortOrder{4}&keywords={5}",
                Page.class, page.getPageNumber(), page.getPageSize(), page.getSortName(), page.getSortOrder(), keywords
        );
        if (page != null && page.getRecords() != null) {
            List<UserInfo> userInfos = new ArrayList<>(page.getRecords().size());
            for (Object o : page.getRecords()) {
                Map userMap = (Map) o;
                UserInfo userInfo = new UserInfo();
                BeanUtils.populate(userInfo, userMap);
                userInfos.add(userInfo);
            }
            page.setRecords(userInfos);
        }
        return page;
    }

    public UserInfo getUserByLoginName(String loginName) {
        return restTemplate.getForObject("http://USERCENTER/user/by/loginName/{1}", UserInfo.class, loginName);
    }

    public List<PermissionInfo> getPermissionByUser(String userId) throws IOException {
        String response = restTemplate.getForObject("http://USERCENTER/permissions/by/user/{1}", String.class, userId);
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, PermissionInfo.class);
        return StringUtils.isEmpty(response) ? null : objectMapper.readValue(response, javaType);
    }

}
